/*
 * @Description: 冒泡排序
 * @Version: 
 * @Author: Weixin Zhu
 * @Date: 2020-12-11 16:15:57
 * @LastEditors: Weixin Zhu
 * @LastEditTime: 2020-12-11 16:59:22
 */
package com.zwx.algorithms.basic;

import com.zwx.algorithms.constant.AlgorithmsConstant;
import com.zwx.algorithms.pub.util.AlgorithmsUtils;
import com.zwx.algorithms.pub.util.LogUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;

public class BubbleSort extends AbstractArraySort {
    static final Logger log = LoggerFactory.getLogger(BubbleSort.class);

    /**
     * @description: 冒泡排序，从左开始排，把小的排前面
     * @param {*}
     * @return {*}
     */
    public Integer[] sort(Integer[] array) {
        int len = array.length;
        int temp = 0;
        for (int i = 1; i < len; i++) {
            for (int j = i - 1; j > -1; j--) {
                totalStep++;
                if (AlgorithmsUtils.needShowStep(len)) {
                    log.debug("index :{},i:{},j:{}", totalStep, i, j);
                }
                if (array[j + 1] < array[j]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                } else {
                    break;
                }
            }
        }
        return array;
    }

    public static void main(String[] args) {
        LogUtils.resetLogLevel(log, org.slf4j.event.Level.INFO);
        Integer[] originArray = null;
        Integer[] sortResult = null;
        AbstractArraySort sort = new BubbleSort();
        StopWatch sw = DateUtil.createStopWatch();
        originArray = AlgorithmsUtils.generateRandomArray(AlgorithmsConstant.MAX_VALUE);
        sw.start();
        sortResult = sort.sort(originArray);
        sw.stop();

        AlgorithmsUtils.printSortedArray(sortResult);
        log.info("size:{},totalStep:{},cost time:{}", sortResult.length, sort.getTotalStep(), sw.getLastTaskTimeMillis());
        log.info(sw.prettyPrint());
    }
}
